﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XcoAppSpaces.Transport.Sockets;
using System.Threading.Tasks;
using XcoAppSpaces.Contracts.Transport;
using System.Threading;

namespace testServer.XcoAppSpaces.SL
{
	class SocketsServer : IDisposable
	{
		private XcoTCPTransportService svc;

		public SocketsServer(int port)
		{
			svc = new XcoTCPTransportService(port);
			svc.OnMessageReceived += (msg, addr, s) => 
			{
				Console.WriteLine("SocketsServer: Message received.");
				Task.Factory.StartNew(() =>
					{
						for (int i = 0; i < 1000; i++)
						{
							var responseMsg = new XcoMessage { Content = BitConverter.GetBytes(i), CausalityContext = new byte[] { 4, 5, 6 }, ContentInfo = "test" };
							Thread.Sleep(1);
							svc.Send(responseMsg, addr);
						}
						Console.WriteLine("SocketsServer: Response messages sent.");
					});
			};

			svc.Start();
		}

		public void Dispose()
		{
			if (svc != null)
				svc.Dispose();
		}
	}
}
